package com.bmc.arsys.demo.javadriver;

import java.io.IOException;

/**
 * Command processor for JavaDriver
 * 
 * @author Yucheng Huang 
 * May 23, 2007
 */
class CommandProcessor {

    final static int SLEEP_ADJUST_FACTOR = 1; 

	CommandProcessor() {
	}

	void randomSleep(long lowerBound, long upperBound) {

		// Get a random number
		int randomValue = JavaDriver.getRandomNumber();

		if (randomValue < 0) {
			randomValue = randomValue * (-1);
		}

		// calculate the sleep seconds
		long sleepSeconds = lowerBound
				+ (randomValue * (upperBound - lowerBound) + ((JavaDriver.RAND_MAX + 1) / 2))
				/ (JavaDriver.RAND_MAX + 1);

		JavaDriver.outputWriter.printResult("\n   Sleeping for " + sleepSeconds
				+ " second(s)\n");
		ThreadControlBlock threadControlBlockObject = JavaDriver
				.getThreadControlBlockPtr();
		if (!threadControlBlockObject.isResultFileOpened()) {
			try {
				Thread.sleep(sleepSeconds * 1000); 
			} catch (InterruptedException e) {
			}
		} else {
			threadControlBlockObject.threadSleep(sleepSeconds * 1000);

		}
	}

	void releaseWaitingThreads() {

		JavaDriver.outputWriter.driverPrintHeader("RELEASE WAITING THREADS");

		ThreadControlBlock threadControlBlockObject = JavaDriver
				.getThreadControlBlockPtr();

		SyncObject releaseObject = threadControlBlockObject.getReleaseObject();
		synchronized (releaseObject) {
			releaseObject.setFlag(true);
			releaseObject.notifyAll();
		}
	}

	void sleepTimer() throws IOException {
		long sleepSeconds = InputReader.getLong("Number of seconds (0): ", 0l);
		JavaDriver.outputWriter.printResult("\n   Sleeping for" + sleepSeconds
				+ " second(s) . . .\n");
		ThreadControlBlock threadControlBlockObject = JavaDriver
				.getThreadControlBlockPtr();
		threadControlBlockObject.threadSleep(sleepSeconds * 1000);
	}

	void millisecondSleepTimer() throws IOException {

		JavaDriver.outputWriter.driverPrintHeader("MILLISECOND SLEEP TIMER");
		long sleepMilliSeconds = InputReader.getLong(
				"Number of milliseconds (0): ", 0l);

		ThreadControlBlock threadControlBlockObject = JavaDriver
				.getThreadControlBlockPtr();
		threadControlBlockObject.threadSleep(sleepMilliSeconds);

	}

	void randomSleepTimer() throws IOException {
		long lowerBound = InputReader.getLong("Lower Bound (0): ", 0l);
		long upperBound = InputReader.getLong("Upper Bound (0): ", 0l);

		if (upperBound < lowerBound) {
			JavaDriver.outputWriter
					.driverPrintError(" **** upper bound is less than lower bound\n");
			return;
		}
		randomSleep(lowerBound, upperBound);
	}

}
